﻿namespace Microsoft.ExternalResearch.CreativeCommons.Common
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Xml;

    /// <summary>
    /// Represents the 'Remove licenses' wizard.
    /// </summary>
    public partial class RemoveLicensesDialog : Form
    {
        /// <summary>
        /// Creates an instance of this class.
        /// </summary>
        public RemoveLicensesDialog()
        {
            this.InitializeComponent();

            this.Text = Helper.GetString("RemoveLicenses");
            this.licenseInfoColumnHeader.Text = Helper.GetString("LicenseInformationHeader");
            this.cancelButton.Text = Helper.GetString("Cancel");
            this.removeButton.Text = Helper.GetString("RemoveLicenses");
            this.selectAllCheckBox.Text = Helper.GetString("SelectAll");
            this.DescriptionLabel.Text = Helper.GetString("ChooseTheLicensesForRemove");

            this.removeButton.Enabled = false;
        }

        /// <summary>
        /// Loads the available licenses.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event arguments.</param>
        private void RemoveLicensesDialogLoad(object sender, EventArgs e)
        {
            this.LoadLicenses();
            this.availableLicensesListView.ItemChecked += new ItemCheckedEventHandler(this.AvailableLicenseslistViewItemChecked);
        }

        /// <summary>
        /// Enable/disable "Remove" button when any item is checked/unchecked.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event arguments.</param>
        private void AvailableLicenseslistViewItemChecked(object sender, ItemCheckedEventArgs e)
        {
            this.removeButton.Enabled = !(0 == this.availableLicensesListView.CheckedItems.Count);
        }

        /// <summary>
        /// Loads and displays the available licenses.
        /// </summary>
        private void LoadLicenses()
        {
            this.availableLicensesListView.Items.Clear();

            if (Directory.Exists(Helper.LocalLicensesFolderPath))
            {
                ImageList imageList = new ImageList();
                imageList.ImageSize = Helper.ImageSize;
                this.availableLicensesListView.SmallImageList = imageList;

                foreach (string dir in Directory.GetDirectories(Helper.LocalLicensesFolderPath))
                {
                    ListViewItem item = new ListViewItem();
                    item.Tag = dir.Substring(Helper.LocalLicensesFolderPath.Length + @"\".Length);

                    if (FileAttributes.Hidden != (File.GetAttributes(dir) & FileAttributes.Hidden))
                    {
                        continue;
                    }
                    string strImageFile = Path.Combine(dir, Helper.LicenseImageFileName);
                    if (!File.Exists(dir + @"\" + Helper.LicenseFileName) || !File.Exists(strImageFile))
                    {
                        continue;
                    }

                    try
                    {
                        Image image = Helper.GetImageFromFile(strImageFile);
                        if (null != image)
                        {
                            imageList.Images.Add(image);
                            item.ImageIndex = imageList.Images.Count - 1;
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        // Ignore if the icon file is missing.
                    }

                    item.Text = Helper.GetLicenseLabel(item.Tag.ToString());
                    this.availableLicensesListView.Items.Add(item);
                }
            }

            this.UpdateUI();
        }

        /// <summary>
        /// Updates the list view when there is no item available in list.
        /// </summary>
        private void UpdateUI()
        {
            if (0 == this.availableLicensesListView.Items.Count)
            {
                ListViewItem item = new ListViewItem();
                item.Text = Helper.GetString("NoLicenseAvailable");
                this.availableLicensesListView.Items.Add(item);
                this.availableLicensesListView.CheckBoxes = false;
            }
            else
            {
                this.availableLicensesListView.CheckBoxes = true;
            }

            this.removeButton.Enabled = !(0 == this.availableLicensesListView.CheckedItems.Count);
        }

        /// <summary>
        /// Removes the selected items from the UI and deleted the corresponding license information fro the local disk.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event arguments.</param>
        private void RemoveButtonClick(object sender, EventArgs e)
        {
            if (DialogResult.No == MessageBox.Show(Helper.GetString("RemoveLicensesMessage"), Helper.GetString("RemoveLicenses"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0))
            {
                return;
            }

            string rootDir = Helper.LocalLicensesFolderPath;
            string errors = String.Empty;

            foreach (ListViewItem item in this.availableLicensesListView.CheckedItems)
            {
                try
                {
                    string dir = Path.Combine(Helper.LocalLicensesFolderPath, item.Tag.ToString());
                    File.SetAttributes(dir, FileAttributes.Archive);
                    Directory.Delete(dir, true);

                    // We need to remove the license image from the disk cache root also.
                    if (File.Exists(dir + ".png"))
                    {
                        File.Delete(dir + ".png");
                    }

                    this.availableLicensesListView.Items.Remove(item);
                }
                catch (IOException)
                {
                    errors += item.Text + "\n";
                }
            }

            if (!String.IsNullOrEmpty(errors))
            {
                Helper.DisplayErrorMessage(Helper.GetString("RemoveLicensesErrorMessage"));
            }

            this.UpdateUI();
        }

        /// <summary>
        /// Selects/unselects all items in list view when "Select All" check box is checked/unchecked.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event arguments.</param>
        private void SelectAllCheckBoxCheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.availableLicensesListView.Items.Count; i++)
            {
                this.availableLicensesListView.Items[i].Checked = this.selectAllCheckBox.Checked;
            }
        }
    }
}
